import { ProCard } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import { Card, Descriptions, Divider, Spin, Tabs, Tag, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import ModalResolve from '../../linkage/components/ModalResolve';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { selectMonitorhcRecord } from '@/services/api/api-monitor-article';
import DetailMonitorArticleContent from './DetailMonitorArticleContent';
import styles from './DetailMonitorArticleContent.less';
import DetailMonitorDisposeContent from '../../dispose/DetailMonitorDisposeContent';
interface DetailsMonitorArticleProps {
  record: MonitorArticleData.RecordPage;
  onRefurbish: () => void;
  triggerMode: 'card' | 'title';
  isLinkage: boolean;
}

const DetailsMonitorArticle: React.FC<DetailsMonitorArticleProps> = ({
  record,
  triggerMode,
  onRefurbish,
  isLinkage,
}) => {
  const access = useAccess();
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState('tab1');
  const [clickId, setClickId] = useState('');
  const [checkTextResult, setCheckTextResultState] = useState<MonitorArticleData.inspectWords[]>(
    [],
  );

  const [details, setDetailsState] = useState<MonitorArticleData.RecordSelect>();

  const [html, setHtmlValueState] = useState<string>('');

  const loadSelectMonitorhcRecord = async () => {
    const res = await selectMonitorhcRecord({
      id: record?.id,
    });
    if (res.code === 0) {
      setDetailsState(res.data);

      if (
        Array.isArray(res.data.greenText.inspectWords) &&
        res.data.greenText.inspectWords.length > 0
      ) {
        const original = res.data.greenText.html
          .replaceAll(`class="word-mark-error-major"`, `class="${styles['word-mark-error-major']}"`)
          .replaceAll(
            `class="word-mark-error-critical"`,
            `class="${styles['word-mark-error-critical']}"`,
          )
          .replaceAll(
            `class="word-mark-error-blocker"`,
            `class="${styles['word-mark-error-blocker']}"`,
          );

        setHtmlValueState(original);
      } else {
        setHtmlValueState(res.data.greenText.html);
      }
      onRefurbish()
    }
  };

  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>
            详情
            {record.violationLevel == undefined || record.violationLevel == 0 ? (
              <Tag icon={<CheckCircleOutlined />} color={'success'}>
                正常
              </Tag>
            ) : record.violationLevel == 1 ? (
              <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                {'警告'}
              </Tag>
            ) : record.violationLevel == 2 ? (
              <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                {'问题'}
              </Tag>
            ) : (
              <Tag icon={<CloseCircleOutlined />} color={'error'}>
                {'告警'}
              </Tag>
            )}
          </div>
          {isLinkage && (
            <div>
              {details?.disposeState === 1 ? (
                // disposeState 为 1 时不渲染任何内容
                <></>
              ) : details?.disposeState === 2 ? (
                <ModalResolve id={details?.id} onRefurbish={loadSelectMonitorhcRecord} />
              ) : details?.disposeState === 3 ? (
                <DetailMonitorDisposeContent data={details} onRefurbish={() => {}} />
              ) : null}
              {/* 你原本的 ModalResolve 仍然需要在 isLinkage 条件下渲染，可按需放置到此 div 内部或外部 */}
            </div>
          )}
        </div>
      }
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
        width: '100%',
      }}
      trigger={
        triggerMode === 'card' ? (
          <div
            style={{
              paddingLeft: 10,
              paddingRight: 10,
              paddingBottom: 10,
            }}
          >
            <Card
              bordered={false}
              hoverable
              style={{
                background: 'linear-gradient(#F5FBFF,#fff, #fff)',
              }}
            >
              <Card.Meta
                title={
                  <div style={{ display: 'flex', justifyContent: 'space-between', width: '73vw' }}>
                    {/* <div> */}
                    <div
                      style={{
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        minWidth: 65,
                      }}
                    >
                      {record?.dataName}
                    </div>
                    <div
                      style={{
                        float: 'left',
                      }}
                    >
                      {!isLinkage ? (
                        <div>
                          {record.violationLevel == undefined || record.violationLevel == 0 ? (
                            <Tag icon={<CheckCircleOutlined />} color={'success'}>
                              正常
                            </Tag>
                          ) : record.violationLevel == 1 ? (
                            <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                              {'警告'}
                            </Tag>
                          ) : record.violationLevel == 2 ? (
                            <Tag icon={<InfoCircleOutlined />} color={'warning'}>
                              {'问题'}
                            </Tag>
                          ) : (
                            <Tag icon={<CloseCircleOutlined />} color={'error'}>
                              {'告警'}
                            </Tag>
                          )}
                        </div>
                      ) : (
                        <Tag
                          icon={
                            record?.disposeState == 1 ? (
                              <QuestionCircleOutlined />
                            ) : record?.disposeState == 2 ? (
                              <ExclamationCircleOutlined />
                            ) : (
                              <CheckCircleOutlined />
                            )
                          }
                          color={
                            record?.disposeState == 1
                              ? 'processing'
                              : record?.disposeState == 2
                              ? '#f50'
                              : 'success'
                          }
                        >
                          {record?.disposeState == 1
                            ? '不需要处置'
                            : record?.disposeState == 2
                            ? '需要处置'
                            : '处置完成'}
                        </Tag>
                      )}
                    </div>
                  </div>
                }
                description={
                  <>
                    <div>
                      <div>平台 :{record.datahubChannelName}</div>
                      <div>账号 : {record.datahubSourceName}</div>
                      <div>
                        单位 :
                        {record.auditSourceResponsibles
                          .map((item) => item.responsibleOrganizationName)
                          .join(',')}
                      </div>
                    </div>
                    <div
                      style={{
                        marginTop: 5,
                        marginRight: 18,
                        display: 'flex',
                        justifyContent: 'space-between',
                        width: '100%',
                      }}
                    >
                      <span
                      // style={{
                      //     color:
                      //         item.run === 1 ? '#F47983' : item.run === 2 ? '#888A8C' : 'orange',
                      // }}
                      >
                        发布时间:{record.dataReleaseTime}
                      </span>
                      <span
                        style={{
                          float: 'right',
                        }}
                      >
                        {/* 记者 : */}
                        {/* {moment(item.claimTime).fromNow()} */}
                      </span>
                    </div>
                  </>
                }
              />
            </Card>
            <div
              style={{
                borderRadius: 12,
                background: '#FFF',
              }}
            ></div>
          </div>
        ) : (
          <a>{record.dataName}</a>
        )
      }
      onVisibleChange={(visible) => {
        if (visible) {
          loadSelectMonitorhcRecord();
        } else {
        }
      }}
      submitter={false}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        {details !== undefined && (
          <>
            <Descriptions title="文章信息">
              <Descriptions.Item label="平台">{details?.datahubChannelName}</Descriptions.Item>
              <Descriptions.Item label="单位">{details?.datahubSourceName}</Descriptions.Item>
              <Descriptions.Item label="账号">{details?.datahubSourceName}</Descriptions.Item>
              <Descriptions.Item label="发布时间">{details?.dataReleaseTime}</Descriptions.Item>
              {/* <Descriptions.Item label="原文链接">
                <a href={details?.sourceUrl} target="_blank">
                  {details?.sourceUrl}{' '}
                </a>
              </Descriptions.Item> */}
            </Descriptions>
            <Divider />
            <Descriptions title="相关负责人">
              {details.auditSourceResponsibles &&
                details.auditSourceResponsibles.map((item) => {
                  return (
                    <>
                      <Descriptions.Item label="负责人">
                        {item.responsibleAccountName}
                      </Descriptions.Item>
                      <Descriptions.Item label="负责人联系方式">
                        {item?.responsibleAccountPhone}
                      </Descriptions.Item>
                      <Descriptions.Item label="负责单位">
                        {item?.responsibleOrganizationName}
                      </Descriptions.Item>
                    </>
                  );
                })}
            </Descriptions>
            <Divider />
            {html && (
              <DetailMonitorArticleContent
                name={details.dataName}
                content={html}
                errorWords={details.greenText.inspectWords ?? []}
                keywords={details?.greenTextKeyword?.greenTextKeywordHits ?? []}
                onRefurbish={function (): void {}}
              />
            )}
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailsMonitorArticle;
